<template>
    <div class="gi_table_page">
    
      <GiTable
      ref="tableRef"
      title="设备分类"
      row-key="id"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="false"
      :disabled-column-keys="['name']"
      @refresh="search"
    >
      <template #expand-icon="{ expanded }">
        <IconDown v-if="expanded" />
        <IconRight v-else />
      </template>
      <template #toolbar-left>
        <a-input v-model="name" placeholder="搜索名称" allow-clear>
          <template #prefix><icon-search /></template>
        </a-input>
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['asset:device:category:create']" type="primary" @click="onAdd()">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['asset:device:category:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>

      
      <template #status="{ record }">
        <GiCellStatus :status="record.status" />
      </template>
      <template #isSystem="{ record }">
        <a-tag v-if="record.isSystem" color="red" size="small">是</a-tag>
        <a-tag v-else color="arcoblue" size="small">否</a-tag>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['asset:device:category:update']" title="修改" @click="onUpdate(record)">修改</a-link>
          <a-link
            v-permission="['asset:device:category:delete']"
            status="danger"
            :disabled="record.isSystem"
            :title="record.isSystem ? '系统内置数据不能删除' : '删除'"
            @click="onDelete(record)"
          >
            删除
          </a-link>
          <a-link v-permission="['asset:device:category:create']" title="新增" @click="onAdd(record.id)">新增</a-link>
        </a-space>
      </template>
      </GiTable>
  
      <DeviceCategoryAddModal ref="DeviceCategoryAddModalRef" :categories="dataList" @save-success="search" />
    </div>
  </template>
  
  <script setup lang="ts">
  import DeviceCategoryAddModal from './DeviceCategoryAddModal.vue'
  import { type DeviceCategoryResp, type DeviceCategoryQuery, deleteDeviceCategory, exportDeviceCategory, listDeviceCategory } from '@/apis/asset/device/category'
  import type { TableInstanceColumns } from '@/components/GiTable/type'
  import { useDownload, useTable } from '@/hooks'
  import { useDict } from '@/hooks/app'
  import { isMobile } from '@/utils'
  import has from '@/utils/has'
  
  defineOptions({ name: 'DeviceCategory' })
  
  const queryForm = reactive<DeviceCategoryQuery>({})
  const tableRef = ref<InstanceType<typeof GiTable>>()
  const {
    tableData,
    loading,
    search,
    handleDelete,
  } = useTable(() => listDeviceCategory(queryForm), {
    immediate: true,
    onSuccess: () => {
      nextTick(() => {
        tableRef.value?.tableRef?.expandAll(true)
      })
    },
  })
  
  // 过滤树
  const searchData = (name: string) => {
    const loop = (data: DeviceCategoryResp[]) => {
      const result = [] as DeviceCategoryResp[]
      data.forEach((item: DeviceCategoryResp) => {
        if (item.name?.toLowerCase().includes(name.toLowerCase())) {
          result.push({ ...item })
        } else if (item.children) {
          const filterData = loop(item.children)
          if (filterData.length) {
            result.push({
              ...item,
              children: filterData,
            })
          }
        }
      })
      return result
    }
    return loop(tableData.value)
  }
  
  const name = ref('')
  const dataList = computed(() => {
    if (!name.value) return tableData.value
    return searchData(name.value)
  })
  
  const columns: TableInstanceColumns[] = [
    { title: '名称', dataIndex: 'name', minWidth: 170, ellipsis: true, tooltip: true },
    { title: '状态', dataIndex: 'status', slotName: 'status', align: 'center' },
    { title: '排序', dataIndex: 'sort', align: 'center', show: false },
    { title: '描述', dataIndex: 'description', ellipsis: true, tooltip: true },
    { title: '创建人', dataIndex: 'createUserString', ellipsis: true, tooltip: true },
    { title: '创建时间', dataIndex: 'createTime', width: 180 },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
      width: 160,
      align: 'center',
      fixed: !isMobile() ? 'right' : undefined,
      show: has.hasPermOr(['asset:device:category:update', 'asset:device:category:delete', 'asset:device:category:create']),
    },
  ]
  
  // 重置
  const reset = () => {
    name.value = ''
  }
  
  // 删除
  const onDelete = (record: DeviceCategoryResp) => {
    return handleDelete(() => deleteDeviceCategory(record.id), {
      content: `是否确定删除该条数据？`,
      showModal: true
    })
  }
  
  // 导出
  const onExport = () => {
    useDownload(() => exportDeviceCategory(queryForm))
  }
  
  const DeviceCategoryAddModalRef = ref<InstanceType<typeof DeviceCategoryAddModal>>()
  // 新增
  const onAdd = (parentId?: string) => {
    DeviceCategoryAddModalRef.value?.onAdd(parentId)
  }
  
  // 修改
  const onUpdate = (record: DeviceCategoryResp) => {
    DeviceCategoryAddModalRef.value?.onUpdate(record.id)
  }
  
  const DeviceCategoryDetailDrawerRef = ref<InstanceType<typeof DeviceCategoryDetailDrawer>>()
  // 详情
  const onDetail = (record: DeviceCategoryResp) => {
    DeviceCategoryDetailDrawerRef.value?.onOpen(record.id)
  }
  </script>
  
  <style scoped lang="scss"></style>
  